/*
 * IntegerCache.java
 * 
 *  author: Daniel Rudigier
 *    date: 02.12.2008
 * 
 * 
 */
package at.syncme.framework.legacy;

/**
 * custom class for caching of java primitives
 * 
 * @author Daniel Rudigier
 */
public class WrapperCache {
    private static final short BUFFER_SIZE = -(-128) + 127 + 1;

    private static final Long longs[] = new Long[BUFFER_SIZE];

    private static final Integer ints[] = new Integer[BUFFER_SIZE];

    private static final Short shorts[] = new Short[BUFFER_SIZE];

    private static final Byte bytes[] = new Byte[BUFFER_SIZE];

    static {
        // create the cache
        for (int i = 0; i < longs.length; i++) {
            longs[i] = new Long(i - 128);
            ints[i] = new Integer(i - 128);
            shorts[i] = new Short((short) (i - 128));
            bytes[i] = new Byte((byte) (i - 128));
        }
    }

    /**
     * return cached long
     * 
     * @param value
     * @return
     */
    public static Long valueOf(long value) {
        final int offset = 128;

        if (value >= -128 && value <= 127) { // must cache
            return longs[(int) value + offset];
        }

        return new Long(value);
    }

    /**
     * return cached integer
     * 
     * @param value
     * @return
     */
    public static Integer valueOf(int value) {
        final int offset = 128;

        if (value >= -128 && value <= 127) { // must cache
            return ints[value + offset];
        }

        return new Integer(value);
    }

    /**
     * return cached short
     * 
     * @param value
     * @return
     */
    public static Short valueOf(short value) {
        final int offset = 128;

        if (value >= -128 && value <= 127) { // must cache
            return shorts[value + offset];
        }

        return new Short(value);
    }

    /**
     * return cached byte
     * 
     * @param value
     * @return
     */
    public static Byte valueOf(byte value) {
        final int offset = 128;

        return bytes[value + offset];
    }
}
